package ore.devops

// 封装HTTP请求
def HttpReq(requestType,requestUrl,requestBody){
    // 定义sonar api接口
    def sonarServer = "http://10.1.10.22:8081/service/rest"
    result = httpRequest authentication: 'nexus-admin-user',
            httpMode: requestType,
            contentType: "APPLICATION_JSON",
            consoleLogResponseBody: true,
            ignotrSslErrors: true,
            requestBody: requestBody,
            url: "${sonarServer}/${requestUrl}",
            quiet: true
    return result
}

// 获取仓库下的所有组件
def GetAllComponents(repoName){
    apiUrl = "v1/components?repository=${repoName}"
    // 发请求
    response = HttpReq("GET",apiUrl,"")
    // json格式化处理
    response = readJSON text: """${response.content}"""
    return response["items"]
}

// 获取组件ID
def GetComponentID(repoName,groupId,artifactId,version){
    // 先获取到所有组件
    results = GetAllComponents(repoName)
    // 然后遍历进行匹配
    for (component in results){
        // 判断
        if (component["group"] == groupId && component["name"] == artifactId && component["version"] == version){
            // 得到id
            id = component["id"]
            return id
        }
    }
}

// 获取单个组件
def GetSingleComponent(repoName,groupId,artifactId,version){
    id = GetComponentID(repoName,groupId,artifactId,version)
    println(id)
    if ("${id}" != null){
        apiUrl = "v1/components/${id}"
        // 发请求
        response = HttpReq("GET",apiUrl,"")
        // json格式化处理
        response = readJSON text: """${response.content}"""
        // 获取downloadUrl
        println(response["assets"]["downloadUrl"])
    }
}


